#!/usr/bin/env node

/**
 * Script to automatically replace critical console statements with safe logger calls
 */

const fs = require('fs');
const path = require('path');
const glob = require('glob');

console.log('🔧 Fixing critical console statements...\n');

// Define which files to process and their logger import requirements
const filesToProcess = [
  {
    pattern: 'electron/services/*.ts',
    loggerImport: "import { log } from '../utils/Logger'\n",
    replacements: [
      {
        from: /console\.log\(`Created version/g,
        to: 'log.version(`Created version'
      },
      {
        from: /console\.log\(`Rolled back/g,
        to: 'log.version(`Rolled back'
      },
      {
        from: /console\.log\(`Deleted version/g,
        to: 'log.version(`Deleted version'
      },
      {
        from: /console\.log\(`Created conversation session/g,
        to: 'log.conversation(`Created conversation session'
      },
      {
        from: /console\.log\(`API key for/g,
        to: 'log.security(`API key for'
      },
      {
        from: /console\.error\(`Failed to store API key/g,
        to: 'log.error(`Failed to store API key'
      },
      {
        from: /console\.error\(`AI Provider Error/g,
        to: 'log.error(`AI Provider Error'
      }
    ]
  }
];

let totalReplacements = 0;

filesToProcess.forEach(({ pattern, loggerImport, replacements }) => {
  const files = glob.sync(pattern, { cwd: path.join(__dirname, '..') });

  files.forEach(file => {
    const filePath = path.join(__dirname, '..', file);
    let content = fs.readFileSync(filePath, 'utf8');
    let fileReplacements = 0;

    // Add logger import if not present
    if (!content.includes('import { log } from')) {
      content = loggerImport + content;
      console.log(`📝 Added logger import to ${file}`);
    }

    // Apply replacements
    replacements.forEach(({ from, to }) => {
      const matches = content.match(from);
      if (matches) {
        content = content.replace(from, to);
        fileReplacements += matches.length;
        console.log(`   ✅ Replaced ${matches.length} occurrence(s) in ${file}`);
      }
    });

    if (fileReplacements > 0) {
      fs.writeFileSync(filePath, content, 'utf8');
      totalReplacements += fileReplacements;
    }
  });
});

console.log(`\n🎉 Complete! Replaced ${totalReplacements} console statements with safe logger calls.`);

// Show remaining console statements
console.log('\n📊 Checking remaining console statements...');

const allFiles = glob.sync('electron/**/*.{ts,js}', { cwd: path.join(__dirname, '..') });
let remainingConsole = 0;

allFiles.forEach(file => {
  const filePath = path.join(__dirname, '..', file);
  const content = fs.readFileSync(filePath, 'utf8');
  const consoleMatches = content.match(/console\.(log|warn|error|info|debug)/g);

  if (consoleMatches) {
    remainingConsole += consoleMatches.length;
  }
});

console.log(`📈 Remaining console statements: ${remainingConsole}`);

if (remainingConsole > 50) {
  console.log('\n💡 Consider running additional manual updates or use the logger more consistently.');
} else {
  console.log('\n✅ Console statement count is now manageable!');
}